<?php
/*
 * @Author: zwx
 * @Date: 2024-05-08 10:39:41
 * @LastEditors: zwx
 * @LastEditTime: 2024-08-30 11:43:08
 * @Description: 私域直播用户
 */

namespace app\apiadmin\controller\user;

use app\apiadmin\controller\liveManager\LiveStatus;
use app\apiadmin\controller\live\MyOrder;
use app\apiadmin\model\system\MemberModel;
use app\apiadmin\model\system\UserModel;
use app\apiadmin\service\data\RedisService;
use app\apiadmin\service\invitation\InvitationService;
use app\apiadmin\service\liveManager\LiveManagerService;
use app\apiadmin\service\order\OrderService;
use app\apiadmin\service\statics\LiveUserGetDataService;
// use app\common\LaneWeChat\core\Wechat;
// use app\common\LaneWeChat\Autoloader;
use app\apiadmin\service\TCSS\TImService;
use app\apiadmin\service\user\UserService;
use app\common\alipay\aop\AlipayTradeService;
use app\common\alipay\aop\AopClient;
//use app\common\service\JwtService;
use app\common\alipay\aop\request\AlipayTradeRefundRequest;
use app\common\alipay\aop\request\AlipayTradeWapPayRequest;
use app\common\alipay\buildermodel\AlipayTradeRefundContentBuilder;
use app\common\controller\BaseController;
use app\common\service\FrontJwtService;
use app\common\utils\Curl;
use app\common\utils\Res;
use app\common\utils\SmsHelper;
use app\Request;
use think\Exception;
use think\facade\Cache;
use think\facade\Db;
use think\facade\Log;

class User extends BaseController
{

    /**
     * @author: oliver
     * @Description: 获取用户类型数组
     * @Date: 2024-05-08 15:41:00
     */
    public function typedata()
    {

        $data = DB::table('xh_siyu_shuziren_flag')->where(array('del' => 0))->select();

        return Res::ok($data);
    }

    /**
     * @author: zwx
     * @Description: 获取用户列表
     * @Date: 2024-05-08 15:41:00
     */
    public function getdata()
    {
        $param = $this->request->param();

        $size = $param['size'] ? $param['size'] : 10; //每页显示条数
        $page = $param['page'] ? $param['page'] : 1; //当前页数

        $type = $param['type'] ? $param['type'] : 1; //昵称或内容
        $input = $param['input'] ? $param['input'] : false; //输入的内容
        $nickname = $param['nickname'] ? $param['nickname'] : false; //输入的内容
        $phone = $param['phone'] ? $param['phone'] : false; //输入的内容
        $flag = $param['flag'] ? $param['flag'] : -1; //用户类型

        $where = array();
        $where[] = ['del', '=', 0];

        //        if ($type == 1) {
        //            if ($input != '' && $input) {
        //                $where[] = array('name', 'like', '%' . $input . '%');
        //            }
        //        } else if ($type == 2) {
        //            if ($input != '' && $input) {
        //                $where[] = array('nickname', 'like', '%' . $input . '%');
        //            }
        //        }
        if ($nickname != '' && $nickname) {
            $where[] = array('nickname', 'like', '%' . $nickname . '%');
        }
        if ($phone != '' && $phone) {
            $where[] = array('phone', 'like', '%' . $phone . '%');
        }

        if ($flag > -1) {
            $where[] = ['flagid', '=', $flag];
        }

        $data = array();
        //        $result = DB::table('xh_siyu_shuziren_list')->where($where)->order('id desc')->page($page,$size)->select();
        //        $count = DB::table('xh_siyu_shuziren_list')->where($where)->count();
        $result = DB::table('xh_siyu_user')->where($where)->order('id desc')->page($page, $size)->select();
        $count = DB::table('xh_siyu_user')->where($where)->count();

        $data = [
            'list' => $result,
            'total' => $count,
        ];

        return Res::ok($data);
    }

    // 手机号登录
    public function login()
    {
        $param = $this->request->param();
        $phone = $param['username'];
        $yanzhengma = $param['yanzhengma'];
        $openid = isset($param['openid']) ? $param['openid'] : '';
        $unionid = isset($param['unionid']) ? $param['unionid'] : '';

        if (Cache::get($phone)) {
            $yanzheng_code = Cache::get($phone)['value'];
            if ($yanzhengma != $yanzheng_code) {
                $result['yanzhengma'] = $yanzhengma;
                $result['yanzheng_code'] = $yanzheng_code;
                $result['code'] = 1;
                $result['message'] = '验证码错误';
                return Res::ok($result);
            }
        } else {
            $result['code'] = 1;
            $result['message'] = '验证码错误';
            return Res::ok($result);
        }

        if ($openid) {
            $where1[] = ['openid', '=', $openid];
            $where1[] = ['del', '=', 0];
            $if_exist1 = DB::table('xh_siyu_user')->where($where1)->order('id desc')->find();
            if (!$if_exist1) { //没有openid的记录
                $where[] = ['phone', '=', $phone];
                $where[] = ['del', '=', 0];
                $if_exist = DB::table('xh_siyu_user')->where($where)->order('id desc')->find();
                if (!$if_exist) {

                    //测试代码小段  测试通过以后删除
                    $d['remark'] = $phone . '我是有opend，数据库没有记录的情况';
                    DB::table('xh_siyu_user_remark')->save($d);

                    $data['phone'] = $phone;
                    $data['nickname'] = '毛毛虫' . time();
                    $data['openid'] = $openid;
                    $data['unionid'] = $unionid;
                    $data['type'] = 1;
                    $data['createtime'] = date("Y-m-d H:i:s");
                    $res = DB::table('xh_siyu_user')->save($data);
                    $if_exist = DB::table('xh_siyu_user')->where($where)->order('id desc')->find();
                }
            } else { //有openid的记录  直接更新手机号
                $data['phone'] = $phone;
                $a = DB::table('xh_siyu_user')->where(array('openid' => $openid))->save($data);
                $if_exist = DB::table('xh_siyu_user')->where($where1)->order('id desc')->find();

                ////测试代码小段  测试通过以后删除
                //$d['remark'] = $phone . '我是有opend，数据库也有记录的情况';
                //DB::table('xh_siyu_user_remark')->save($d);
                ////先用手机号查一下是不是之前网页上注册过
                //$where[] = ['phone', '=', $phone];
                //$where[] = ['del', '=', 0];
                //$if_exist_phone = DB::table('xh_siyu_user')->where($where)->order('id desc')->find();
                //if ($if_exist_phone) {
                //    //之前注册过，更新之前的那条数据
                //    $data['phone'] = $phone;
                //    $data['nickname'] = $if_exist1['nickname'];
                //    $data['openid'] = $if_exist1['openid'];
                //    $data['unionid'] = $if_exist1['unionid'];
                //    $data['wx_avatarurl'] = $if_exist1['wx_avatarurl'];
                //    $data['type'] = 0;
                //    $res = DB::table('xh_siyu_user')->where(array('id' => $if_exist_phone['id']))->save($data);
                //
                //    //$data1['del'] = 1;
                //    //$res = DB::table('xh_siyu_user')->where(array('id' => $if_exist1['id']))->save($data1);
                //
                //    $a = DB::table('xh_siyu_user')->where(array('openid' => $openid))->save($data);
                //    $if_exist = DB::table('xh_siyu_user')->where($where1)->order('id desc')->find();
                //} else {
                //    $data['phone'] = $phone;
                //    $a = DB::table('xh_siyu_user')->where(array('openid' => $openid))->save($data);
                //    $if_exist = DB::table('xh_siyu_user')->where($where1)->order('id desc')->find();
                //}

            }
        } else {

            $where[] = ['phone', '=', $phone];
            $where[] = ['del', '=', 0];
            $if_exist = DB::table('xh_siyu_user')->where($where)->order('id desc')->find();
            if (!$if_exist) {
                //测试代码小段  测试通过以后删除
                $d['remark'] = $phone . '我是本地没有opend，数据库也没有记录的情况';
                DB::table('xh_siyu_user_remark')->save($d);
                $data['phone'] = $phone;
                $data['nickname'] = '毛毛虫' . time();
                $data['type'] = 1;
                $data['createtime'] = date("Y-m-d H:i:s");
                $res = DB::table('xh_siyu_user')->save($data);
                $if_exist = DB::table('xh_siyu_user')->where($where)->order('id desc')->find();
            }
        }

        $IMClient = new TImService();
        $ret = $IMClient->account_import_one($this->addPreToAccout($if_exist['id']), $if_exist['nickname'], $if_exist['wx_avatarurl']);
        $user_info['id'] = $if_exist['id'];
        $user_info['name'] = $if_exist['name'];
        $user_info['nickname'] = $if_exist['nickname'];
        $user_info['phone'] = $if_exist['phone'];
        $user_info['openid'] = $if_exist['openid'];
        $user_info['createtime'] = $if_exist['createtime'];
        $user_info['type'] = $if_exist['type'];
        $user_info['wx_avatarurl'] = $if_exist['wx_avatarurl'];
        Cache::set('user_info', $user_info, 60);
        $result['user_id'] = $user_info['id'];
        $result['phone'] = $user_info['phone'];
        $result['code'] = 0;
        $result['message'] = '登录成功';

        $mute = $IMClient->user_mute($this->addPreToAccout($result['user_id'])); // 禁言

        $expireTime = 0;
        // 返回前增加token
        $result['front_token'] = FrontJwtService::createToken($user_info, $expireTime);
        $result['front_token_expireTime'] = $expireTime;

        return Res::ok($result);
    }

    public function sendVerifycode()
    {
        $param = $this->request->param();
        $phone = $param['phone'];
        $phones[] = $phone;

        $code = rand(1000, 9999);
        SmsHelper::sendCaptchaSms($phones, [$code]);
        $generator = [
            'value' => $code,
            'key' => '',
        ];
        Cache::set($phone, $generator, 300);
        //        $user_info['id'] = 1;
        //        $user_info['name'] = '乔峰';
        //        $user_info['phone'] = $phone;
        //        Cache::set('user_info'  ,$user_info, 60);
        //        $a = Cache::get('user_info');
        //        Cache::delete($name);

        //测试代码小段  测试通过以后删除
        $d['remark'] = '手机号' . $phone . '收到的验证码是' . $code;
        DB::table('xh_siyu_user_remark')->save($d);

        $data['yanzhengma_code'] = $code;
        //        $data['user_info'] = $a;
        $data['code'] = 200;
        $data['message'] = '我准备发送了,号码是' . $phone;
        return Res::ok($data);
    }

    // 微信统一登录
    public function wxUnificationLogin()
    {
        $appid = env('wx.appid', 'wxa2c49bf999540a91');
        $secret = env('wx.secret', 'ad1458baf1b5c591cb64517819328b78');
        $param = $this->request->param();
        $code = $param["code"] ?? '';
        $redirect_uri = $param["redirect_uri"] ?? '';
        $login_url = $param["login_url"] ?? '';
        $live_id = $param["live_id"] ?? '';
        $tutor_id = $param["tutor_id"] ?? '';
        $params = [
            'live_id' => $live_id,
            'tutor_id' => $tutor_id,
            'ip' => getClientIp(),
            'code' => $code,
            'login_url' => $login_url,
            'redirect_uri' => $redirect_uri,
            'log_host' => $param['host'] ?? '',
            'log_oauth2_url' => $param['oauth2_url'] ?? '',
            'system' => $param['system'] ?? '',
            'network_type' => $param['network_type'] ?? '',
            'web_user_agent' => $param['web_user_agent'] ?? '',
        ];
        $get_token_url = 'https://api.weixin.qq.com/sns/oauth2/access_token?appid=' . $appid . '&secret=' . $secret . '&code=' . $code . '&grant_type=authorization_code';
        $json_obj = Curl::callWebServer($get_token_url);
        try {
            $params['api_host'] = 'api.weixin.qq.com/sns/oauth2/access_token';
            $params['api_errcode'] = $json_obj['errcode'] ?? '';
            $params['api_data'] = json_encode($json_obj, JSON_UNESCAPED_UNICODE);
            $params['add_time'] = date('Y-m-d H:i:s', time());
            Db::table('xh_siyu_live_login_log')->insert($params);
        } catch (\Exception $e) {
            return Res::error($e->getMessage());
        }
        if (!empty($json_obj['errcode'])) {
            return Res::error(json_encode($json_obj));
        }
        $access_token = $json_obj['access_token'];
        $openid = $json_obj['openid'];
        $info_url = "https://api.weixin.qq.com/sns/userinfo" . "?access_token=" . $access_token . "&openid=" . $openid . "&lang=zh_CN";
        $json_obj_user = Curl::callWebServer($info_url);
        try {
            $params['api_host'] = 'api.weixin.qq.com/sns/userinfo';
            $params['api_errcode'] = $json_obj_user['errcode'] ?? '';
            $params['api_data'] = json_encode($json_obj_user, JSON_UNESCAPED_UNICODE);
            $params['add_time'] = date('Y-m-d H:i:s', time());
            Db::table('xh_siyu_live_login_log')->insert($params);
        } catch (\Exception $e) {
            return Res::error($e->getMessage());
        }
        if (!empty($json_obj_user['errcode'])) {
            return Res::error(json_encode($json_obj_user));
        }
        $data = UserService::getWxLogin(['oauth' => $json_obj, 'info' => $json_obj_user, 'redirect_uri' => $redirect_uri]);
        return Res::ok($data);
    }

    // 登录成功后操作：建立im账号，禁言，创建token
    public function wxLoginAfterExecute()
    {
        // im账号创建
        // im禁言
        // 订单验证
        // 重复观看验证

        $param = $this->request->param();
        $prefix = $param['prefix'] ?? '';
        $mid = $param['mid'];
        if (empty($mid)) {
            return Res::error('参数错误');
        }
        $exist = DB::table('xh_siyu_user')->where('union_md5', $mid)->find();

        $IMClient = new TImService();
        $IMClient->account_import_one($prefix . $exist['id'], $exist['nickname'], $exist['wx_avatarurl']); //创建IM账号
        $IMClient->user_mute($prefix . $exist['id']); // 禁言

        // 创建token，时限0无限
        $exist['front_token'] = FrontJwtService::createToken($exist);

        return Res::ok($exist);
    }

    public function wxlogin()
    {
        $appid = env('wx.appid', 'wxa2c49bf999540a91');
        $secret = env('wx.secret', 'ad1458baf1b5c591cb64517819328b78');
        $param = $this->request->param();
        $code = $param["code"];
        $get_token_url = 'https://api.weixin.qq.com/sns/oauth2/access_token?appid=' . $appid . '&secret=' . $secret . '&code=' . $code . '&grant_type=authorization_code';
        $json_obj = Curl::callWebServer($get_token_url);
        if (!empty($json_obj['errcode'])) {
            return Res::error(json_encode($json_obj));
        }
        $access_token = $json_obj['access_token'];
        $openid = $json_obj['openid'];
        $info_url = "https://api.weixin.qq.com/sns/userinfo" . "?access_token=" . $access_token . "&openid=" . $openid . "&lang=zh_CN";
        $json_obj_user = Curl::callWebServer($info_url);
        if (!empty($json_obj_user['errcode'])) {
            return Res::error(json_encode($json_obj_user));
        }
        $nickname = $json_obj_user['nickname'];
        $headimgurl = $json_obj_user['headimgurl'];
        $unionid = $json_obj_user['unionid'];

        //信息入库
        $where[] = ['unionid', '=', $unionid];
        $where[] = ['del', '=', 0];
        $if_exist = DB::table('xh_siyu_user')->where($where)->find();
        if (empty($if_exist)) {
            $data['openid'] = $openid;
            $data['unionid'] = $unionid;
            $data['union_md5'] = md5($unionid);
            $data['nickname'] = $nickname;
            $data['wx_avatarurl'] = $headimgurl;
            $data['type'] = 0;
            $data['status'] = 1;
            $data['status_ch'] = '已登录';
            $data['createtime'] = date("Y-m-d H:i:s");
            $resId = DB::table('xh_siyu_user')->insertGetId($data);
            if ($resId > 0) {
                $data['id'] = $resId;
                $if_exist = $data;
            } else {
                return Res::error('登录入库失败');
            }
        }

        $IMClient = new TImService();
        $IMClient->account_import_one($this->addPreToAccout($if_exist['id']), $nickname, $headimgurl); //创建IM账号
        $IMClient->user_mute($this->addPreToAccout($if_exist['id'])); // 禁言

        // 创建token，时限0无限
        FrontJwtService::createToken($if_exist);

        return Res::ok($if_exist['union_md5']);
    }

    //微信登录
    public function get_wx_info()
    {
        $param = $this->request->param();

        $nickname = '';
        $headimgurl = '';
        $openid = '';
        $access_token = '';
        //正式
        $appid = env('wx.appid', 'wxa2c49bf999540a91');
        $secret = env('wx.secret', 'ad1458baf1b5c591cb64517819328b78');
        //测试
        // $appid = 'wx0fab109c92fdc064';
        // $secret = '8669027ee218e818c719fd7eacc865ea';
        $code = $param["code"];
        //        $to_url = $_GET["to_url"];
        $get_token_url = 'https://api.weixin.qq.com/sns/oauth2/access_token?appid=' . $appid . '&secret=' . $secret . '&code=' . $code . '&grant_type=authorization_code';
        $json_obj = Curl::callWebServer($get_token_url);
        if (empty($json_obj['access_token'])) {
            return Res::error('获取微信用户信息失败');
        }
        $access_token = $json_obj['access_token'];
        $openid = $json_obj['openid'];
        //测试代码小段  测试通过以后删除
        $d1['remark'] = '微信用户获取后台接口' . json_encode($json_obj);
        DB::table('xh_siyu_user_remark')->save($d1);

        $info_url = "https://api.weixin.qq.com/sns/userinfo" . "?access_token=" . $access_token . "&openid=" . $openid . "&lang=zh_CN";
        $json_obj_user = Curl::callWebServer($info_url);

        $nickname = $json_obj_user['nickname'];
        $headimgurl = $json_obj_user['headimgurl'];
        $unionid = $json_obj_user['unionid'];

        //测试代码小段  测试通过以后删除
        $d['remark'] = '微信用户获取后台接口' . json_encode($json_obj_user);
        DB::table('xh_siyu_user_remark')->save($d);

        if ($openid) {
            $where[] = ['openid', '=', $openid];
            $where[] = ['del', '=', 0];
            $if_exist = DB::table('xh_siyu_user')->where($where)->order('id desc')->find();
            if (empty($if_exist)) {
                $data1['openid'] = $json_obj_user['openid'];
                $data1['unionid'] = $json_obj_user['unionid'];
                $data1['nickname'] = $json_obj_user['nickname'];
                $data1['wx_avatarurl'] = $json_obj_user['headimgurl'];
                $data1['type'] = 0;
                $data1['status'] = 1;
                $data1['status_ch'] = '已登录';
                $data1['createtime'] = date("Y-m-d H:i:s");
                $resId = DB::table('xh_siyu_user')->insertGetId($data1);
                $if_exist = DB::table('xh_siyu_user')->where('id=' . $resId)->find();
                $data['userid'] = $if_exist['id'];
                $data['phone'] = '';
            } else {
                $data['phone'] = $if_exist['phone'];
                $data['userid'] = $if_exist['id'];
            }
        }

        //创建IM账号
        $IMClient = new TImService();
        $ret = $IMClient->account_import_one($this->addPreToAccout($data['userid']), $nickname, $headimgurl);

        $data['nickname'] = $nickname;
        $data['headimgurl'] = $headimgurl;
        $data['openid'] = $openid;
        $data['unionid'] = $unionid;

        $mute = $IMClient->user_mute($this->addPreToAccout($data['userid'])); // 禁言

        // 返回前增加token
        $expireTime = 0;
        $data['front_token'] = FrontJwtService::createToken($if_exist, $expireTime);
        $data['front_token_expireTime'] = $expireTime;

        $data['message'] = 'ok';
        return Res::ok($data);
    }

    // 预约
    public function yuyue_zhibo()
    {
        $param = $this->request->param();
        $liveId = $param['liveId'] ?? null;
        $tutorId = $param['tutorId'] ?? null;
        $user_id = $param['user_id'] ?? null;
        if (empty($liveId) || empty($user_id) || empty($tutorId)) {
            $data2['code'] = 0;
            $data2['message'] = '预约失败，缺少直播间信息或者用户信息';
            return Res::ok($data2);
        }

        $yyWhere[] = ['user_id', '=', $user_id];
        $yyWhere[] = ['liveId', '=', $liveId];
        $yyWhere[] = ['status', '=', 2];
        $zhibo = DB::table('xh_siyu_live_yuyue')->where($yyWhere)->order('id desc')->count();
        if ($zhibo > 0) {
            return Res::ok(['message' => '已经预约']);
        }

        $zhibojian_info = DB::table('xh_siyu_live_manager')->where('id', '=', $liveId)->find();
        $data['liveId'] = $liveId;
        $data['title'] = $zhibojian_info['title'];
        $data['status'] = 2;
        $data['status_ch'] = '已预约';
        $data['start_time'] = $zhibojian_info['start_time'];
        $data['end_time'] = $zhibojian_info['end_time'];
        $data['user_id'] = $user_id;
        DB::table('xh_siyu_live_yuyue')->save($data);
        $data1['status'] = 2; //把主表的状态改成已预约
        $data1['status_ch'] = '已预约'; //把主表的状态改成已预约
        DB::table('xh_siyu_user')->where('id', '=', $user_id)->save($data1);

        /***** MongoDb 入库 *****/
        $tutorInfo = MemberModel::findByUid($tutorId);
        $userInfo = UserModel::findById($user_id);
        $i_data = [
            'live_id' => $liveId, // 直播ID
            'tutor_id' => $tutorId, // 助教ID
            'tutor_nickname' => $tutorInfo['nick_name'] ?? null, // 助教昵称
            'user_id' => $user_id, // 用户ID
            'open_id' => $userInfo['openid'] ?? null, // 用户ID
            'nickname' => $userInfo['nickname'] ?? null, // 用户昵称
            'headimgurl' => $userInfo['wx_avatarurl'] ?? null, // 用户头像
            'phone' => $userInfo['phone'] ?? null, // 用户手机号
            'status' => 1, // 1:预约 2:签到
        ];
        $i_update = InvitationService::addOrEdit($i_data);

        $data2['message'] = '预约成功';
        $data2['i_update'] = $i_update;
        return Res::ok($data2);
    }
    public function create_zhibo_info()
    {
        $param = $this->request->param();
        $user_id = isset($param['user_id']) ? $param['user_id'] : '';
        $liveId = isset($param['liveId']) ? $param['liveId'] : '';
        $where1[] = ['user_id', '=', $user_id];
        $where1[] = ['liveId', '=', $liveId];
        $zhibo_main_info = DB::table('xh_siyu_live_yuyue_main')->where($where1)->order('id desc')->select();
        if (count($zhibo_main_info) != 0) {
            $data2['code'] = 1;
            $data2['message'] = '本场次直播已经建立过数据';
            return Res::ok($data2);
        } else {
            $where2[] = ['id', '=', $liveId];
            $zhibojian_info = DB::table('xh_siyu_live_manager')->where($where2)->order('id desc')->find();
            $data['liveId'] = $liveId;
            $data['title'] = $zhibojian_info['title'];
            $data['status'] = 1;
            $data['status_ch'] = '已登录';
            $data['start_time'] = $zhibojian_info['start_time'];
            $data['end_time'] = $zhibojian_info['end_time'];
            $data['user_id'] = $user_id;
            $res = DB::table('xh_siyu_live_yuyue_main')->save($data);

            $data2['code'] = 0;
            $data2['message'] = '成功建立本场次直播客户关联数据';

            $where3[] = ['user_id', '=', $user_id];
            $where3[] = ['liveId', '=', $liveId];
            $zhibo_main = DB::table('xh_siyu_live_yuyue_main')->where($where3)->order('id desc')->find();

            $data1['liveId'] = $liveId;
            $data1['title'] = $zhibojian_info['title'];
            $data1['status'] = 1;
            $data1['status_ch'] = '已登录';
            $data1['start_time'] = $zhibojian_info['start_time'];
            $data1['end_time'] = $zhibojian_info['end_time'];
            $data1['user_id'] = $user_id;
            $res = DB::table('xh_siyu_live_yuyue')->save($data1);

            return Res::ok($data2);
        }
    }

    // 获取状态
    public function check_zhibo()
    {
        //0、暂无直播（参数不对）
        //1、未预约
        //2、已预约
        //3、直播中
        //4、已结束
        //5、未匹配到订单，需要用户验证订单
        //6、被踢
        //7、直播已看过
        $status = 0;

        $param = $this->request->param();
        $user_id = $param['user_id'] ?? null;
        $liveId = $param['liveId'] ?? null;
//        $planId = $param['planId'] ?? null;

        if (empty($user_id)) {
            return Res::error('参数不对，用户ID不得为空');
        }
        if (empty($liveId)) {
            return Res::ok(['status' => $status]);
        }
//        if (empty($planId)) {
        //            return Res::error('参数不对，邀约计划ID不得为空');
        //        }

        $IMClient = new TImService();
        $mute = $IMClient->user_mute($this->addPreToAccout($user_id), $liveId); // 禁言

        $yyWhere = [
            'liveId' => $liveId,
            'user_id' => $user_id,
        ];
        $yyCount = DB::name('siyu_live_yuyue')->where($yyWhere)->count();
        $liveIndo = DB::name('siyu_live_manager')->where(['id' => $liveId])->find();

        if ($liveIndo['status'] == 0) {
            //未开播
            if ($yyCount > 0) {
                //已预约
                $status = 2;
            } else {
                //未预约
                $status = 1;
            }
        } elseif ($liveIndo['status'] == 1) {
            //直播中
            $status = 3;
        } elseif ($liveIndo['status'] == 2) {
            //已结束
            $status = 4;
        } else {
            //错误
            $status = 0;
        }

        $is_watched = LiveManagerService::isWatchedLiveContent($liveId, $user_id);
        if ($is_watched) {
            //是否看过直播内容
            $status = 7;
        }
        if (env('Live.validate_order')) {
            $validate = OrderService::validate_order($user_id, $liveId); // 验证订单
            if ($validate['status'] > 0) {
                $status = 5;
            }
        } else {
            $validate = ['status' => 0, 'order' => []];
        }
        return Res::ok(['status' => $status, 'validata' => $validate, 'cover' => $liveIndo['conver'], 'mute' => $mute, 'watched' => $is_watched]);
        //return Res::ok(['status' => $status, 'validata' => [], 'cover' => $liveIndo['conver'], 'mute' => $mute]);
    }

    // 获取订单
    public function get_order()
    {
        $param = $this->request->param();
        $liveId = $param['liveId'] ?? 0;
        $userId = $param['userId'] ?? 0;
        $phone = $param['phone'] ?? 0;
        if (empty($liveId)) {
            return Res::error('直播ID不得为空');
        }
        if (empty($userId)) {
            return Res::error('用户未登录');
        }
        if (empty($phone)) {
            return Res::error('手机号不得为空');
        }
        $user = DB::table('xh_siyu_user')->where('id', $userId)->find();
        $query = 'sy_user_id=' . $userId . ' and (sy_user_phone=' . $phone . ' or validate_phone=' . $phone . ') and xh_order_id is not null and zhujiao is not null';
        $order = DB::table('xh_siyu_user_order_zhujiao')->where($query)->find();
        $rela = true;
        if (empty($order)) {
            $query = '`tel` = ' . $phone . ' and `pay_time` is not null';
            $order = DB::table('xh_order_1')->where($query)->order('wx_union_id desc, pay_time desc')->find();
            $rela = false;
        }
        if (empty($order)) {
            $status = 0;
        } else {
            $status = 5;
            $unionId = $order['wx_union_id'] ?? $order['xh_order_union_id'];
            if (empty($unionId)) {
                return Res::ok(['status' => $status, 'order' => $order]);
            }
            if (empty($rela)) {
                //首次登录他人订单
                OrderService::validate_order_relation($user, $order, $phone);
            }
            OrderService::validate_order_log($liveId, $status, $user, $order, $phone);
            if ($unionId != $user['unionid']) {
                //手机号验证通过，但当前用户与订单用户不匹配，踢掉订单用户
                $order_user = DB::table('xh_siyu_user')->where('unionid', $unionId)->find();
                if (empty($order_user)) {
                    //订单用户未登录过私域，绑定订单
                } else {
                    //订单用户登录过私域，踢掉订单用户
                    $redis = RedisService::makeService();
                    $redis->publish("live_info_event", json_encode([
                        "liveId" => '' . $liveId,
                        "command" => "kick_user",
                        "params" => [
                            "user_id" => '' . $order_user['id'],
                        ],
                    ]));
                }
            }
        }

        return Res::ok(['status' => $status, 'order' => $order]);

    }

    public function check_phone_exist()
    {
        $param = $this->request->param();
        $open_id = isset($param['open_id']) ? $param['open_id'] : null;

        $where2[] = ['openid', '=', $open_id];
        $res = DB::table('xh_siyu_user')->where($where2)->find();
        if ($res && $res['phone']) {
            $data2['code'] = 0;
            $data2['msg'] = '有手机号';
        } else {
            $data2['code'] = 3;
            $data2['msg'] = '没有手机号 或者 没用户数据';
        }

        return Res::ok($data2);
    }

    public function sign_zhibo()
    { //直播签到
        $param = $this->request->param();
        $liveId = $param['liveId'] ?? null;
        $tutorId = $param['tutorId'] ?? null;
        $user_id = $param['user_id'] ?? null;
        if (empty($liveId) || empty($user_id) || empty($tutorId)) {
            $data2['code'] = 0;
            $data2['message'] = '签到失败，缺少直播间信息或者用户信息';
            return Res::ok($data2);
        }

        $where2[] = ['liveId', '=', $liveId];
        $where2[] = ['user_id', '=', $user_id];
        $where2[] = ['status', '=', 3];
        $zhibo = DB::table('xh_siyu_live_yuyue')->where($where2)->count();
        if ($zhibo > 0) {
            $data2['code'] = 1;
            $data2['message'] = '已经签到';
            return Res::ok($data2);
        }

        $where[] = ['id', '=', $liveId];
        $zhibojian_info = DB::table('xh_siyu_live_manager')->where($where)->order('id desc')->find();
        $data['liveId'] = $liveId;
        $data['title'] = $zhibojian_info['title'];
        $data['status'] = 3;
        $data['status_ch'] = '已签到';
        $data['start_time'] = $zhibojian_info['start_time'];
        $data['end_time'] = $zhibojian_info['end_time'];
        $data['user_id'] = $user_id;
        DB::table('xh_siyu_live_yuyue')->save($data);
        $data1['status'] = 3; //把主表的状态改成已预约
        $data1['status_ch'] = '已签到'; //把主表的状态改成已预约
        DB::table('xh_siyu_user')->where('id', '=', $user_id)->save($data1);

        /***** MongoDb 入库 *****/
        $tutorInfo = MemberModel::findByUid($tutorId);
        $userInfo = UserModel::findById($user_id);
        $i_data = [
            'live_id' => $liveId, // 直播ID
            'tutor_id' => $tutorId, // 助教ID
            'tutor_nickname' => $tutorInfo['nick_name'] ?? null, // 助教昵称
            'user_id' => $user_id, // 用户ID
            'open_id' => $userInfo['openid'] ?? null, // 用户ID
            'nickname' => $userInfo['nickname'] ?? null, // 用户昵称
            'headimgurl' => $userInfo['wx_avatarurl'] ?? null, // 用户头像
            'phone' => $userInfo['phone'] ?? null, // 用户手机号
            'status' => 2, // 1:预约 2:签到
        ];
        $i_update = InvitationService::addOrEdit($i_data);

        $data2['code'] = 0;
        $data2['message'] = '签到成功';
        $data2['i_update'] = $i_update;
        return Res::ok($data2);
    }

    public function check_login()
    {
        $param = $this->request->param();
        $openid = isset($param['openid']) ? $param['openid'] : '';

        $where[] = ['openid', '=', $openid];
        $res = DB::table('xh_siyu_user')->where($where)->order('id desc')->find();

        if ($res) {
            $IMClient = new TImService();
            $ret = $IMClient->account_import_one($this->addPreToAccout($res['id']), $res['nickname'], $res['wx_avatarurl']);
        }

        //如果openid不存在
        if (!$res) {
            $data2['code'] = 3;
        }
        if ($res) {
            $data2['phone'] = $res['phone'];
            $data2['message'] = 'aaaa';
            $data2['res'] = $res;
            $data2['ret'] = $ret;
        } else {
            $data2['phone'] = '';
            $data2['message'] = '数据库没数据';
            $data2['res'] = '';
            $data2['ret'] = '';
        }
        return Res::ok($data2);
    }

    /**
     * @author: crg
     * @Description: 获取用户详情
     * @Date: 2024-05-16 09:49:51
     */
    public function getUserInfo()
    {
        $param = $this->request->post();
        $input = $param['id'] ? $param['id'] : false; //输入的内容

        $where = array();
        $where[] = ['del', '=', 0];
        if ($input) {
            $where[] = array('id', '=', $input);
        }

        $result = DB::table('xh_siyu_user')->where($where)->find();
        return Res::ok($result);

    }

    public function alih5pay($total_amount, $out_trade_no, $notify_url)
    {

        $notify_url = '域名' . $notify_url;
        $config = config('aliPay');

        // code...
        try {
            // 实例化 AopClient
            $aop = new \AopClient();

            // 支付宝网关地址
            $aop->gatewayUrl = $config['gatewayUrl'];

            // 支付宝APPID
            $aop->appId = '';

            // 开发者私钥
            $aop->rsaPrivateKey = $config['rsaPrivateKey'];

            // 返回格式
            $aop->format = $config['format'];

            // 字符编码utf8
            $aop->charset = $config['charset'];

            // 加密方式
            $aop->signType = $config['signType'];

            // 请填写支付宝公钥，一行字符串
            $aop->alipayrsaPublicKey = $config['alipayrsaPublicKey'];

            //实例化具体API对应的request类,类名称和接口名称对应,当前调用接口名称：alipay.trade.app.pay
            $request = new \AlipayTradeWapPayRequest();

            // 下单数据
            $bizcontent = [];
            $bizcontent['body'] = lang('购买商品') . "-" . $out_trade_no; // 交易的具体描述信息。
            $bizcontent['subject'] = lang('购买商品，订单号：') . $out_trade_no; // 商品的标题/交易标题/订单标题/订单关键字
            $bizcontent['out_trade_no'] = "$out_trade_no"; // 唯一订单号
            $bizcontent['timeout_express'] = '30m'; // 该笔订单允许的最晚付款时间，逾期将关闭交易
            $bizcontent['total_amount'] = (String) round($total_amount / 100, 2); // 订单总金额，单位为元
            $bizcontent['product_code'] = 'QUICK_WAP_WAY'; // 销售产品码，商家和支付宝签约的产品码，为固定值QUICK_MSECURITY_PAY
            $bizcontent = json_encode($bizcontent, 256);

            // 回调地址
            $request->setNotifyUrl("$notify_url");

            // 设置下单数据
            $request->setBizContent($bizcontent);

            //这里和普通的接口调用不同，使用的是sdkExecute
            $response = $aop->pageExecute($request);

            if (!$response) {
                $data = [];
                $data['code'] = 201;
                $data['msg'] = lang('error');
                return $data;
            }
            $data['code'] = 200;
            $data['msg'] = lang('success');
            $data['data'] = $response;
            return $data;
        } catch (\Exception $e) {
            $data = [];
            $data['code'] = 201;
            $data['msg'] = lang('error');
            return $data;
        }
    }

    //     public function getAlipay()
    //     {
    //         $param = $this->request->param();
    //         //        $front_token = $param['front_token'];
    //         if (isset($param['orderid'])) {
    //             $orderid = $param['orderid'];
    //             $where[] = array('id', '=', $orderid);
    //             $order_info = DB::table('xh_siyu_order')->where($where)->find();
    //         } else {
    //             //纯测试用数据
    //             $order_info['order_num'] = 'SY1716522039509189';
    //             $order_info['fee'] = 1;
    //         }
    //         //            require "../../../common/alipay/aop/AopClient.php";  //引入alipay文件
    //         //            require "../../../common/alipay/aop/request/AlipayTradeWapPayRequest.php";  //引入alipay文件
    //         //配置支付宝相关参数
    //         $config = [
    //             //以下是正式环境的参数
    //             'alipay_appid' => '2021004147620033',
    //             'alipay_alipay_rsapublicKey' => 'MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAhxB6iK/ic/9quQOow4pBuB7k4LrezPfx8rg1QYIU8Zvne5Ldh14FdUId4s19pd8km6j+n9gdMkKzBA4yGQxGzSII+fS7kVp1sfvNJiSIhVszdL1Kzpx1n+LPkedF4sXxBYoagPQsbRVo8IoPIl0iTvXZvU/crWMfulhXspTottUPrL1E7GZYP9Sr0GrKZID7IQOOsVYPNjgcqe4qVxrx0Qukaa4F4Roe6WiNM8FviQUWdZhds5mez+o+5Y5B0oE50N8qVemK7yLdAx9LphKTKhGWAvg8UC2pptez5xEtM6aVmgFYZz5Bzcmc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bluHeiOWTh12u56S4/l2rVwuxeCuxFT30BuPC8gjUdzkHZc3hGeLXSvp+7xLbhGu6pNIJUgOMwkPmwKBgQC42clCD5yxRIyA7nkqocE8hBIge2Bl8lC1shNVMt3VL1aZhwXgh/FrTxqa+9ru1QvqxjU1IVImhbs2z9Ru+u1TvjsacXztu00Sr1eM2iAGtL1RixfI7N8SKnJbQA5iHweB5x/8hrEm/7cWQDKuEHX+JX4b5T2CFNdR79VYVZpZCQKBgQCybdeff10Lf3uLo5O2/sxzc9GX/ZWU3ZNcFQE52esGGa/KIk02iSjQ20bNkOyAc9ebVo9JoJPydtBkKGW1IgOYaxvwPuP8YuK9MEcy1vdkvj4BeENH8Edf8HsjabEKUwbxRMsSenvXPpKH/g6MVrPDrHip6QRRq0Mp44tmYOCf4wKBgQCtDZo2+dIORMGaQquk2l0Z5/1koEe9izn0fI7UJeV5RPqHSSTjSfjSUhKqGN87o7HZ6gAbnOY/6hzRv/bNFtvvIZkP1AR5A2lc/gpsIGAxEJtHzJyuckfx6fRhkh4w4NMZ8b0KDO3BAbaDnH5qMINK074OXSEL5cIMUabgeAmOJg==',
    //             'alipay_notify' => 'https://liveapi.banxued.com/apiadmin/user/alipay_notify',
    //             //以下是沙箱环境的参数
    //             //                'alipay_appid' =>'9021000137631512',
    //             //                'alipay_alipay_rsapublicKey' =>'MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAo7whnUDKUW8asSA4DGxRIvKA+NLY0rkJXYRLRQDY4QKvMe6S6GAgGgDIi8+USQDplscHumDPykTz0FDQJoS7SYzQcTUZgn15G4GbxFdqLRkokpIikfm2BpagtF/MZOsZkfX82zw43UOHJS1Y4k7BoDTSpifhf4RR+murN9bZvT17iqCSOhwGy84/epp91ad6mqmerzjCX4mYyNipTG+HrOw20iWdLas1PFo5edk6o7XZdnUByPYw6QdnwFTvOUvwIEuRVm7aoPE+x0w/Rl2fEogwWO7BSNPuyo3EU1u00cqy1wc0f+GhD59GSrtno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CSecPckK9KU0hft4ksuLm0FJVZrpkn3IZKnY75w8CgYAs85tY7bpWX9J884FUqNRf8m4Os4gZYB24W2mlpe2Gr2YqUMxGBdbiiTwYjqgmTI04leGEx6pMfpj6nn9c0PB4nYb2RiTQF6TO2681OGAqY2QQAUNmRzImb8OIZn9GOETtQtb/JAqERHlJXXFVRobUm2WwHr+Qjnyppqi+6gvBAQKBgQC3ACF7eGDa1n8gr2meaWwukJflCI4QfJDmStLbNeJCsKl9yaenWw7+K/BJ8imKhOsjjV38TgKcKDK5s5Uamt7RPNpYEBkvvDtduaPeMzTbOicsppkaPX/5d2fu1yxrvGemFe1V94Cgv1B2CE+F7171s4V/Hvc0Vk5maxNbfixEVQKBgQCpsdIdrUWizpATwvYhdp/oeb7/YWw/4Zqs/pSmJGYunD3BMwzLLWI71Gd9n0ui3ODlhkKY6SPkOQHNVKx6ZXbOmbxiDiNPDyfu5cHqakYdtve5ztz2qUHlGKuI5lYESrN7YqM4z1DOtp3uXsWm/Nle0+3rruZThr1HNOxCYLm6mg==',
    //             //                'alipay_notify' =>'https://liveapi.banxued.com/apiadmin/user/alipay_notify2',
    //             //支付宝回调地址 支付成功后支付宝会把消息发送给此接口，在此接口中完成支付成功后的相关操作即可
    //         ];

    //         $aop = new AopClient();

    //         //            $aop->gatewayUrl = "https://openapi-sandbox.dl.alipaydev.com/gateway.do"; //网关地址要使用沙箱网关alipaydev
    //         $aop->gatewayUrl = "https://openapi.alipay.com/gateway.do"; //网关地址要使用沙箱网关alipaydev

    //         //支付宝分配给开发者的应用ID
    //         $aop->appId = $config['alipay_appid'];

    //         //请填写支付宝公钥，一行字符串
    //         $aop->alipayrsaPublicKey = $config['alipay_alipay_rsapublicKey'];

    //         //请填写开发者私钥去头去尾去回车，一行字符串
    //         $aop->rsaPrivateKey = $config['alipay_rsaprivateKey'];

    //         //            返回数据格式
    //         $aop->format = "json";

    //         // 表单提交字符集编码
    //         $aop->postCharset = "utf-8";

    //         //签名类型
    //         $aop->signType = "RSA2";

    //         //api版本
    //         $aop->apiVersion = '1.0';
    //         //实例化具体API对应的request类,类名称和接口名称对应,当前调用接口名称：alipay.trade.app.pay
    //         $request = new AlipayTradeWapPayRequest();
    //         //SDK已经封装掉了公共参数，这里只需要传入业务参数，沙箱环境的product_code只能是FAST_INSTANT_TRADE_PAY
    //         $info = [
    //             'body' => 'xxx',
    //             'subject' => '标题',
    //             //                'out_trade_no'=>time().rand(1111,9999),
    //             //                'total_amount'=>0.03,
    //             'out_trade_no' => $order_info['order_num'],
    //             'total_amount' => $order_info['fee'] / 100,
    //             //                    &#39;body&#39; => &#39;xxx&#39;,
    //             //                &#39;subject&#39; => &#39;标题&#39;,  //订单标题。
    //             //                &#39;out_trade_no&#39; => time().rand(1111,9999),  //商户网站唯一订单号 自定义的订单号
    //             //                &#39;total_amount&#39; => 1, //订单总金额。单位为元，精确到小数点后两位，取值范围：[0.01,100000000] 。
    //         ];
    //         $info = json_encode($info, JSON_UNESCAPED_UNICODE);

    //         //支付宝服务器主动通知商户服务器里指定的页面http/https路径。 支付回调
    //         $request->setNotifyUrl($config['alipay_notify']);
    //         $request->setReturnUrl(env('Live.live_host') . "/pages/animate/myorder/paysuccess?id=" . $order_info['id'] . '&event_id=' . $param['event_id']);
    //         $request->setBizContent($info);
    //         //这里和普通的接口调用不同，使用的是sdkExecute
    //         $result = $aop->pageExecute($request);

    //         return Res::ok($result);

    //     }

    public function alipay_notify2()
    {
        //测试代码小段  测试通过以后删除
        $d['remark'] = "我是支付宝支付成功以后的回调地址，测试成功回调到地址，我是11";
        DB::table('xh_siyu_user_remark')->save($d);

        $param = $this->request->param();
        if (isset($param)) {
            $d1['remark'] = "我是支付宝支付成功以后给回传的数据" . json_encode($param);
            DB::table('xh_siyu_user_remark')->save($d1);
        }
        //        $json = '{"gmt_create":"2024-05-24 11:40:47","charset":"utf-8","seller_email":"3685225548@qq.com","subject":"\u6807\u9898","sign":"VHT3KgRcx2QQXKnRzyL+tRjXtTdcMeCz\/hvrHrtNkmdtpwHHPIMrkasle0WCDMJcMW\/iWpV1XavAvDCFfu98Ea2WBd7rsWOJZIryO0MzdFwqiR+pVwqsSJG+i5Ny4AVXToD+5LzxVcoTKXyKindhw4divy2chBgLVSO6xtAqQ0RJpVqoTUJybOtnPNMXQcDUcq13yyRBnjF5jsG9OMzoWNnRbzOl+TEX4ncJqtb5SWnIcua4LvXmGoPSn+vrL2\/bjhiJXjxpZQxRN4jj2H41FozwQLhY0jbL+ObsIrYqdry2CnpT9l+zn2+irvRBwLteekCne4mTyxLmGRyEKjF9ng==","body":"xxx","buyer_open_id":"030e_66V3wspFNbwKO0JSozg-_t5QBC9uzeJgXRdMWGyr0f","invoice_amount":"0.01","notify_id":"2024052401222114048034301498659076","fund_bill_list":"[{\"amount\":\"0.01\",\"fundChannel\":\"ALIPAYACCOUNT\"}]","notify_type":"trade_status_sync","trade_status":"TRADE_SUCCESS","receipt_amount":"0.01","buyer_pay_amount":"0.01","app_id":"2021004147620033","sign_type":"RSA2","seller_id":"2088741819227733","gmt_payment":"2024-05-24 11:40:47","notify_time":"2024-05-24 11:40:48","merchant_app_id":"2021004147620033","version":"1.0","out_trade_no":"SY1716522039509188","total_amount":"0.01","trade_no":"2024052422001434301401771058","auth_app_id":"2021004147620033","buyer_logon_id":"471***@qq.com","point_amount":"0.00"}';
        //        $param = json_decode($json,true);
        //        $_POST = $param;
        $config = [
            //应用ID,您的APPID。
            'app_id' => "2021004147620033",
            //商户私钥，您的原始格式RSA私钥
            'merchant_private_key' => "MIIEvwIBADANBgkqhkiG9w0BAQEFAASCBKkwggSlAgEAAoIBAQCKjaocI+7fATTGEiyw2GyH61/ieyox2eD+ei0asaJDzxn07DbQpZ66uPqURDER6qJtQRvtghu2NP/qJAIfwQ6FJo7lsaDEPEqK6lxTbuV3eYKLAJjp/Z2Rf1aANkF2uA5XCCDmMZGg2FgSCXjR2XZywM+JhTdFjgSuzJ5ySRgQiPOzOmP2VoYEj7eNyOaXDfRhUUlm8holtzXp84Lf9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yAc9ebVo9JoJPydtBkKGW1IgOYaxvwPuP8YuK9MEcy1vdkvj4BeENH8Edf8HsjabEKUwbxRMsSenvXPpKH/g6MVrPDrHip6QRRq0Mp44tmYOCf4wKBgQCtDZo2+dIORMGaQquk2l0Z5/1koEe9izn0fI7UJeV5RPqHSSTjSfjSUhKqGN87o7HZ6gAbnOY/6hzRv/bNFtvvIZkP1AR5A2lc/gpsIGAxEJtHzJyuckfx6fRhkh4w4NMZ8b0KDO3BAbaDnH5qMINK074OXSEL5cIMUabgeAmOJg==",
            //异步通知地址
            'notify_url' => "https://liveapi.banxued.com/apiadmin/user/alipay_notify",
            //同步跳转
            'return_url' => "https://baidu.com",
            //编码格式
            'charset' => "UTF-8",
            //签名方式(在你生成秘钥的时候，选择的加密方式)
            'sign_type' => "RSA2",
            //支付宝网关（这个是默认的，不用管它）
            'gatewayUrl' => "https://openapi.alipay.com/gateway.do",
            //支付宝公钥,查看地址：https://openhome.alipay.com/platform/keyManage.htm 对应APPID下的支付宝公钥。
            'alipay_public_key' => "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAhxB6iK/ic/9quQOow4pBuB7k4LrezPfx8rg1QYIU8Zvne5Ldh14FdUId4s19pd8km6j+n9gdMkKzBA4yGQxGzSII+fS7kVp1sfvNJiSIhVszdL1Kzpx1n+LPkedF4sXxBYoagPQsbRVo8IoPIl0iTvXZvU/crWMfulhXspTottUPrL1E7GZYP9Sr0GrKZID7IQOOsVYPNjgcqe4qVxrx0Qukaa4F4Roe6WiNM8FviQUWdZhds5mez+o+5Y5B0oE50N8qVemK7yLdAx9LphKTKhGWAvg8UC2pptez5xEtM6aVmgFYZz5Bzcmcrff0RM2BzADIch8IkI//1VtRpfv5uwIDAQAB",
            //日志路径
            'log_path' => "",
        ];
        $arr = $_POST;
        $alipaySevice = new AlipayTradeService($config);
        $alipaySevice->writeLog(var_export($_POST, true));
        $check = $alipaySevice->check($arr);
        //        var_dump($result);
        //        $aop = new AopClient();
        //        $aop->gatewayUrl = "https://openapi.alipay.com/gateway.do";
        //        $aop->appId = $config['app_id'];
        //        $aop->method = 'alipay.trade.wap.pay';
        //        $aop->charset = 'utf-8';
        //        $aop->signType = 'RSA2';
        //        $aop->alipayrsaPublicKey = $config['alipay_public_key'];
        //        $aop->rsaPrivateKey = $config['merchant_private_key'];
        //        //使用rsaCheckV1方法检验回调数据是否合法，最后的返回值是一个布尔值
        //        //中间的参数，它要的是公钥的路径，但是我再上面给公钥设置了值，所以直接填空就行，他就会找字符串的公钥
        //        $check=$aop->rsaCheckV1($_POST,'',$_POST['sign_type']);

        if (isset($check)) {
            $d1['remark'] = "我是支付宝支付回调验签的的结果check=" . $check;
            DB::table('xh_siyu_user_remark')->save($d1);
        }
        //测试代码小段  测试通过以后删除
        $d['remark'] = "我是支付宝支付成功以后的回调地址，测试成功回调到地址，我是22";
        DB::table('xh_siyu_user_remark')->save($d);
        if ($check) {
            //返回值里面$_POST['trade_status']是支付结果的信息
            $oo = Db::name('siyu_order')->where(['order_num' => $_POST['out_trade_no']])->find();
            if ($oo && $_POST['trade_status'] == 'TRADE_SUCCESS' && $oo['state'] == 0) {
                echo 'success';
                //我这里设置的是，如果返回值是支付成功，那么就把这个订单状态给改状态
                //out_trade_no这个是返回的订单号

                // 获取公域订单
                $unionId = Db::table('xh_siyu_user_order_zhujiao_log')->where(['live_id' => $oo['liveId'], 'user_id' => $oo['user_id']])->value('xh_order_union_id');
                //如果是链接购买
                if (!$unionId) {
                    $unionId = $oo['wx_unionid'];
                }

                $orderId = LiveManagerService::checkXhOrder($unionId);

                $data['state'] = 1;
                $data['trade_no'] = $_POST['trade_no'];
                $data['pay_time'] = $_POST['gmt_payment'];
                $data['trade_state_desc'] = '支付成功';
                $data['order_id'] = !empty($orderId) ? $orderId : 0;
                Db::name('siyu_order')->where(['order_num' => $_POST['out_trade_no']])->save($data);
                //删除改价key
                if ($oo['key']) {
                    $redis = \app\apiadmin\service\data\RedisService::makeService();
                    $redis->del($oo['key']);
                }
                //关联定金
                if ($oo['deposit_ids']) {
                    $deposit_ids = explode(',', $oo['deposit_ids']);
                    if ($deposit_ids) {
                        foreach ($deposit_ids as $id) {
                            $deposit_info = DB::table('xh_siyu_deposit')->where(['id' => $id])->field('actual_payment_fee,pay_time')->find();
                            if (!$deposit_info) {
                                continue;
                            }
                            $data = [
                                'siyu_order_id' => $oo['id'],
                            ];
                            DB::table('xh_siyu_deposit')->where(array('id' => $id))->save($data);
                            //定金金额更新到订单表
                            $update_data = [
                                'deposit_first_fee' => $deposit_info['actual_payment_fee'],
                                'deposit_first_time' => $deposit_info['pay_time'],
                            ];
                            DB::table('xh_siyu_order')->where(['id' => $oo['id']])->update($update_data);
                        }
                    }
                }

                $o = Db::name('siyu_order')->where(['order_num' => $_POST['out_trade_no']])->find();

                //打日志，做记录
                $m = [];
                $m['liveId'] = $o['liveId'];
                $m['live_user_id'] = $o['user_id'];
                $s = db::table('xh_siyu_invitation_user_signin')->where($m)->find();
                if ($s) {
                    $a = [];
                    $a['chengjiao'] = 3;
                    $a['chengjiao_time'] = date('Y-m-d H:i:s');
                    $a['order_num'] = $o['order_num'];
                    db::table('xh_siyu_invitation_user_signin')->where($m)->save($a);
                } else {
                    $a = [];
                    $a['liveId'] = $o['liveId'];
                    $a['live_user_id'] = $o['user_id'];
                    $a['order_num'] = $o['order_num'];
                    $a['chengjiao'] = 3;
                    $a['chengjiao_time'] = date('Y-m-d H:i:s');
                    db::table('xh_siyu_invitation_user_signin')->insertGetId($a);
                }

                //统计提单数据
                $liveId = $o['liveId']; // 直播ID
                $liveStatus = new LiveStatus($o['liveId']);
                $liveStatus->set_xiaoshoue_yifukuan(intval($o['fee']));
                $liveStatus->set_xiadan_danshu_yifukuan($o['order_num']);
                $liveStatus->set_xiadan_rensu_yifukuan($o['user_id']);

                $liveStatus->remove_xiaoshoue_weifukuan(intval($o['fee']));
                $liveStatus->remove_xiadan_danshu_weifukuan($o['order_num']);
                $liveStatus->remove_xiadan_renshu_weifukuan($o['user_id']);

                //更新行为记录添加数据详情
                // $collection = 'live_order';
                // $map = [];
                // $map['liveId'] = $liveId;
                // $map['order_num'] = $o['order_num'];

                // $update = ['$set' => ['pay_time' => $data['pay_time'], 'state' => 1]];
                // $liveOrder = new LiveUserGetDataService($collection);
                // $liveOrder->updateOrder($map, $update);

                // $d['remark'] = date('Y-m-d H:i:s') . '--arr------' . json_encode($arr);
                // DB::table('xh_siyu_user_remark')->save($d);

                //行为记录添加数据详情
                $collection = 'live_event';
                $liveOrder = new LiveUserGetDataService($collection);

                $map = [];
                $map['user_id'] = $o['user_id'] . '';
                $map['liveId'] = $liveId;

                $update = ['$set' => ['event' => '下单']];
                $r = $liveOrder->updateEvent($map, $update);

                MyOrder::afterPayOrder($o);

                // 新增/修改 公域订单状态
                if (!empty($orderId)) {
                    $session = Db::table('xh_siyu_live_manager')->where('id', $liveId)->value('venue');
                    LiveManagerService::getLiveOrderState($liveId, $session, $orderId, 3, $o['wx_unionid'], $o['tutorId'], $o['id'], $o['fee']);
                }

                //注意，一定要echo 一个success，因为支付宝没有在页面看到success的话，还会继续发回调信息

                echo 'success';
            }
            //定金
            $dd = Db::name('siyu_deposit')->where(['deposit_num' => $_POST['out_trade_no']])->find();
            if ($dd && $_POST['trade_status'] == 'TRADE_SUCCESS' && $dd['state'] == 0) {
                // echo 'success';

                $data['state'] = 1;
                $data['trade_no'] = $_POST['trade_no'];
                $data['pay_time'] = $_POST['gmt_payment'];
                $data['actual_payment_fee'] = $dd['fee'];
                $data['trade_state_desc'] = '支付成功';
                Db::name('siyu_deposit')->where(['deposit_num' => $_POST['out_trade_no']])->save($data);

                //注意，一定要echo 一个success，因为支付宝没有在页面看到success的话，还会继续发回调信息

                echo 'success';
            }

        }

    }

    public function test1()
    {
        $config = [
            //应用ID,您的APPID。
            'app_id' => "2021004147620033",
            //商户私钥，您的原始格式RSA私钥
            'merchant_private_key' => "MIIEvwIBADANBgkqhkiG9w0BAQEFAASCBKkwggSlAgEAAoIBAQ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ge2Bl8lC1shNVMt3VL1aZhwXgh/FrTxqa+9ru1QvqxjU1IVImhbs2z9Ru+u1TvjsacXztu00Sr1eM2iAGtL1RixfI7N8SKnJbQA5iHweB5x/8hrEm/7cWQDKuEHX+JX4b5T2CFNdR79VYVZpZCQKBgQCybdeff10Lf3uLo5O2/sxzc9GX/ZWU3ZNcFQE52esGGa/KIk02iSjQ20bNkOyAc9ebVo9JoJPydtBkKGW1IgOYaxvwPuP8YuK9MEcy1vdkvj4BeENH8Edf8HsjabEKUwbxRMsSenvXPpKH/g6MVrPDrHip6QRRq0Mp44tmYOCf4wKBgQCtDZo2+dIORMGaQquk2l0Z5/1koEe9izn0fI7UJeV5RPqHSSTjSfjSUhKqGN87o7HZ6gAbnOY/6hzRv/bNFtvvIZkP1AR5A2lc/gpsIGAxEJtHzJyuckfx6fRhkh4w4NMZ8b0KDO3BAbaDnH5qMINK074OXSEL5cIMUabgeAmOJg==",
            //异步通知地址
            'notify_url' => "https://liveapi.banxued.com/apiadmin/user/alipay_notify",
            //同步跳转
            'return_url' => "https://baidu.com",
            //编码格式
            'charset' => "UTF-8",
            //签名方式(在你生成秘钥的时候，选择的加密方式)
            'sign_type' => "RSA2",
            //支付宝网关（这个是默认的，不用管它）
            'gatewayUrl' => "https://openapi.alipay.com/gateway.do",
            //支付宝公钥,查看地址：https://openhome.alipay.com/platform/keyManage.htm 对应APPID下的支付宝公钥。
            'alipay_public_key' => "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAhxB6iK/ic/9quQOow4pBuB7k4LrezPfx8rg1QYIU8Zvne5Ldh14FdUId4s19pd8km6j+n9gdMkKzBA4yGQxGzSII+fS7kVp1sfvNJiSIhVszdL1Kzpx1n+LPkedF4sXxBYoagPQsbRVo8IoPIl0iTvXZvU/crWMfulhXspTottUPrL1E7GZYP9Sr0GrKZID7IQOOsVYPNjgcqe4qVxrx0Qukaa4F4Roe6WiNM8FviQUWdZhds5mez+o+5Y5B0oE50N8qVemK7yLdAx9LphKTKhGWAvg8UC2pptez5xEtM6aVmgFYZz5Bzcmcrff0RM2BzADIch8IkI//1VtRpfv5uwIDAQAB",
            //日志路径
            'log_path' => "",
        ];

        // 初始化SDK
        $alipayClient = new AopClient();
        //配置支付宝相关参数
        $config = [
            //以下是正式环境的参数
            'alipay_appid' => '2021004147620033',
            'alipay_alipay_rsapublicKey' => 'MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAhxB6iK/ic/9quQOow4pBuB7k4LrezPfx8rg1QYIU8Zvne5Ldh14FdUId4s19pd8km6j+n9gdMkKzBA4yGQxGzSII+fS7kVp1sfvNJiSIhVszdL1Kzpx1n+LPkedF4sXxBYoagPQsbRVo8IoPIl0iTvXZvU/crWMfulhXspTottUPrL1E7GZYP9Sr0GrKZID7IQOOsVYPNjgcqe4qVxrx0Qukaa4F4Roe6WiNM8FviQUWdZhds5mez+o+5Y5B0oE50N8qVemK7yLdAx9LphKTKhGWAvg8UC2pptez5xEtM6aVmgFYZz5Bzcmcrff0RM2BzADIch8IkI//1VtRpfv5uwIDAQAB',
            'alipay_rsaprivateKey' => 'MIIEvwIBADANBgkqhkiG9w0BAQEFAASCBKkwggSlAgEAAoIBAQCKjaocI+7fATTGEiyw2GyH61/ieyox2eD+ei0asaJDzxn07DbQpZ66uPqURDER6qJtQRvtghu2NP/qJAIfwQ6FJo7lsaDEPEqK6lxTbuV3eYKLAJjp/Z2Rf1aANkF2uA5XCCDmMZGg2FgSCXjR2XZywM+JhTdFjgSuzJ5ySRgQiPOzOmP2VoYEj7eNyOaXDfRhUUlm8holtzXp84Lf9Mlq6Wy2qruzk6AtArM9ZEwb1DOPFussgr0z/dGcbQ/k/+DmUx/nQJ+IV7MZ/Oa9ZhAW1nu8gLiON/8+pKYrGQQYNJi4SkQj/YAixsZoaAGouOvnYdvR7V76GYodwQM0/zOzAgMBAAECggEACLIFWAjFSAeaWUfwuBSNEyapeNxD9Kb44N+oDwHQ7jKELYPZmN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bNFtvvIZkP1AR5A2lc/gpsIGAxEJtHzJyuckfx6fRhkh4w4NMZ8b0KDO3BAbaDnH5qMINK074OXSEL5cIMUabgeAmOJg==',
            'alipay_notify' => 'https://liveapi.banxued.com/apiadmin/user/alipay_notify',
            //以下是沙箱环境的参数
            //                'alipay_appid' =>'9021000137631512',
            //                'alipay_alipay_rsapublicKey' =>'MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAo7whnUDKUW8asSA4DGxRIvKA+NLY0rkJXYRLRQDY4QKvMe6S6GAgGgDIi8+USQDplscHumDPykTz0FDQJoS7SYzQcTUZgn15G4GbxFdqLRkokpIikfm2BpagtF/MZOsZkfX82zw43UOHJS1Y4k7BoDTSpifhf4RR+murN9bZvT17iqCSOhwGy84/epp91ad6mqmerzjCX4mYyNipTG+HrOw20iWdLas1PFo5edk6o7XZdnUByPYw6QdnwFTvOUvwIEuRVm7aoPE+x0w/Rl2fEogwWO7BSNPuyo3EU1u00cqy1wc0f+GhD59GSrtnoF3mcGuNBjfqjTX0UmlkE+i0jwIDAQAB',
            //                'alipay_rsaprivateKey' =>'MIIEpAIBAAKCAQEAo7whnUDKUW8asSA4DGxRIvKA+NLY0rkJXYRLRQDY4QKvMe6S6GAgGgDIi8+USQDplscHumDPykTz0FDQJoS7SYzQcTUZgn15G4GbxFdqLRkokpIikfm2BpagtF/MZOsZkfX82zw43UOHJS1Y4k7BoDTSpifhf4RR+murN9bZvT17iqCSOhwGy84/epp91ad6mqmerzjCX4mYyNipTG+HrOw20iWdLas1PFo5edk6o7XZdnUByPYw6QdnwFTvOUvwIEuRVm7aoPE+x0w/Rl2fEogwWO7BSNPuyo3EU1u00cqy1wc0f+GhD59GSrtnoF3mcGuNBjfqjTX0UmlkE+i0jwIDAQABAoIBABwRCaoNCyE+bFLkdPccMiRNcXI1olkswsA3BzgC1ypq7WEfxirzH02VyMq+gGqrL19bKqX2JmhDvY996tBPfFM1Qh3FvmOx4mqmou7bFSY548yMJETliy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DOtp3uXsWm/Nle0+3rruZThr1HNOxCYLm6mg==',
            //                'alipay_notify' =>'https://liveapi.banxued.com/apiadmin/user/alipay_notify',
            //支付宝回调地址 支付成功后支付宝会把消息发送给此接口，在此接口中完成支付成功后的相关操作即可
        ];

        //        $aop = new AopClient();

        //            $aop->gatewayUrl = "https://openapi-sandbox.dl.alipaydev.com/gateway.do"; //网关地址要使用沙箱网关alipaydev
        $alipayClient->gatewayUrl = "https://openapi.alipay.com/gateway.do"; //网关地址要使用沙箱网关alipaydev

        //支付宝分配给开发者的应用ID
        $alipayClient->appId = $config['alipay_appid'];

        //请填写支付宝公钥，一行字符串
        $alipayClient->alipayrsaPublicKey = $config['alipay_alipay_rsapublicKey'];

        //请填写开发者私钥去头去尾去回车，一行字符串
        $alipayClient->rsaPrivateKey = $config['alipay_rsaprivateKey'];

        //            返回数据格式
        $alipayClient->format = "json";

        // 表单提交字符集编码
        $alipayClient->postCharset = "utf-8";

        //签名类型
        $alipayClient->signType = "RSA2";

        //api版本
        $alipayClient->apiVersion = '1.0';

        // 构造请求参数以调用接口
        //        $request = new AlipayTradeRefundRequest();
        //        $model = array();

        // 设置商户订单号
        //        $model['out_trade_no'] = "20150320010101001";

        // 设置查询选项
        //        $queryOptions = array();
        //        $queryOptions[] = "refund_detail_item_list";
        //        $model['query_options'] = $queryOptions;

        // 设置退分账明细信息
        //        $refundRoyaltyParameters = array();
        //        $refundRoyaltyParameters0 = array();
        //        $refundRoyaltyParameters0['amount'] = "0.1";
        //        $refundRoyaltyParameters0['trans_in'] = "2088101126708402";
        //        $refundRoyaltyParameters0['royalty_type'] = "transfer";
        //        $refundRoyaltyParameters0['trans_out'] = "2088101126765726";
        //        $refundRoyaltyParameters0['trans_out_type'] = "userId";
        //        $refundRoyaltyParameters0['royalty_scene'] = "达人佣金";
        //        $refundRoyaltyParameters0['trans_in_type'] = "userId";
        //        $refundRoyaltyParameters0['trans_in_name'] = "张三";
        //        $refundRoyaltyParameters0['desc'] = "分账给2088101126708402";
        //        $refundRoyaltyParameters[] = $refundRoyaltyParameters0;
        //        $model['refund_royalty_parameters'] = $refundRoyaltyParameters;

        // 设置支付宝交易号
        $model['trade_no'] = "2024052422001434301459699843";

        // 设置退款金额
        $model['refund_amount'] = "0.01";

        // 设置退款包含的商品列表信息
        //        $refundGoodsDetail = array();
        //        $refundGoodsDetail0 = array();
        //        $refundGoodsDetail0['out_sku_id'] = "outSku_01";
        //        $refundGoodsDetail0['out_item_id'] = "outItem_01";
        //        $refundGoodsDetail0['goods_id'] = "apple-01";
        //        $refundGoodsDetail0['refund_amount'] = "19.50";
        //        $refundGoodsDetail[] = $refundGoodsDetail0;
        //        $model['refund_goods_detail'] = $refundGoodsDetail;

        // 设置退款原因说明
        $model['refund_reason'] = "正常退款";

        // 设置针对账期交易
        //        $model['related_settle_confirm_no'] = "2024041122001495000530302869";

        // 设置退款请求号
        $model['out_request_no'] = "HZ01RF001";

        //        $alipaySevice = new AlipayTradeService($config);
        //        $refund = $alipaySevice->Refund();

        //        $request->setBizContent(json_encode($model,JSON_UNESCAPED_UNICODE));
        //        $responseResult = $alipayClient->execute($request);
        //        $responseApiName = str_replace(".","_",$request->getApiMethodName())."_response";
        //        $response = $responseResult->$responseApiName;
        //        if(!empty($response->code)&&$response->code==10000){
        //            echo("调用成功");
        //        }
        //        else{
        //            echo("调用失败");
        //        }
    }

    //    public  function test($out_trade_no="",$refund_fee=0){
    public function test2()
    {
        //配置支付宝相关参数
        $config = [
            //以下是正式环境的参数
            'alipay_appid' => '2021004147620033',
            'alipay_alipay_rsapublicKey' => 'MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAhxB6iK/ic/9quQOow4pBuB7k4LrezPfx8rg1QYIU8Zvne5Ldh14FdUId4s19pd8km6j+n9gdMkKzBA4yGQxGzSII+fS7kVp1sfvNJiSIhVszdL1Kzpx1n+LPkedF4sXxBYoagPQsbRVo8IoPIl0iTvXZvU/crWMfulhXspTottUPrL1E7GZYP9Sr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1M+mRXRYay7uSG63nSbMj3cKRiJyQKBgQC0wcQeJkSOninfAHXetue/Y4G39/sqiDbGBnSQs6RufIn+OkEtdxaBH0mwf+9aj47KYp1cXwqKwa6lEl1W5NxcEeNCt4aTbluHeiOWTh12u56S4/l2rVwuxeCuxFT30BuPC8gjUdzkHZc3hGeLXSvp+7xLbhGu6pNIJUgOMwkPmwKBgQC42clCD5yxRIyA7nkqocE8hBIge2Bl8lC1shNVMt3VL1aZhwXgh/FrTxqa+9ru1QvqxjU1IVImhbs2z9Ru+u1TvjsacXztu00Sr1eM2iAGtL1RixfI7N8SKnJbQA5iHweB5x/8hrEm/7cWQDKuEHX+JX4b5T2CFNdR79VYVZpZCQKBgQCybdeff10Lf3uLo5O2/sxzc9GX/ZWU3ZNcFQE52esGGa/KIk02iSjQ20bNkOyAc9ebVo9JoJPydtBkKGW1IgOYaxvwPuP8YuK9MEcy1vdkvj4BeENH8Edf8HsjabEKUwbxRMsSenvXPpKH/g6MVrPDrHip6QRRq0Mp44tmYOCf4wKBgQCtDZo2+dIORMGaQquk2l0Z5/1koEe9izn0fI7UJeV5RPqHSSTjSfjSUhKqGN87o7HZ6gAbnOY/6hzRv/bNFtvvIZkP1AR5A2lc/gpsIGAxEJtHzJyuckfx6fRhkh4w4NMZ8b0KDO3BAbaDnH5qMINK074OXSEL5cIMUabgeAmOJg==',
            'alipay_notify' => 'https://liveapi.banxued.com/apiadmin/user/alipay_notify',
        ];
        $aop = new AopClient;
        $aop->gatewayUrl = 'https://openapi.alipay.com/gateway.do';
        $aop->appId = $config['alipay_appid'];
        $aop->rsaPrivateKey = $config['alipay_rsaprivateKey'];
        $aop->alipayrsaPublicKey = $config['alipay_alipay_rsapublicKey'];
        $aop->apiVersion = '1.0';
        $aop->signType = 'RSA2';
        $aop->postCharset = 'utf-8';
        $aop->format = 'json';

        $request = new AlipayTradeRefundRequest;
        //        $request->setNotifyUrl($config['alipay_notify']);
        $info = [
            'trade_no' => '2024052522001434301408069968',
            'refund_amount' => 0.01,
        ];
        $info = json_encode($info, JSON_UNESCAPED_UNICODE);

        $request->setBizContent($info);
        $result = $aop->execute($request);
        //        $result = $aop->pageExecute($request);

        $alipaySevice = new AlipayTradeService($config);
        //        $alipaySevice->writeLog(var_export($_POST,true));

        $builder = new AlipayTradeRefundContentBuilder();
        $builder->setTradeNo('2024052522001434301408069968');
        $builder->setRefundAmount(0.01);
        //$builder->tradeNo = '2024052522001434301408069968';
        //$builder->refund_amount = 0.01;

        $arr = $builder->getBizContent();
        $request->buildModel();
        $check = $alipaySevice->Refund($arr);

        var_dump($result);
        die;

        $responseNode = str_replace(".", "_", $request->getApiMethodName()) . "_response";
        $resultCode = $result->$responseNode->code;

        if (!empty($resultCode) && $resultCode == 10000) {
            $status = 1;
            $message = "退款成功";
        } else {
            $status = 0;
            $message = $result->alipay_trade_refund_response->sub_msg;
        }
        return ['status' => $status, 'message' => $message];
    }

    public static function alipay_refund($trade_no, $refund_amount, $out_trade_no, $out_request_no, $part_type)
    {
        //        echo '123';die;
        //        $param = $this->request->param();
        $config = [
            //应用ID,您的APPID。
            'app_id' => "2021004147620033",
            //商户私钥，您的原始格式RSA私钥
            'merchant_private_key' => "MIIEvwIBADANBgkqhkiG9w0BAQEFAASCBKkwggSlAgEAAoIBAQCKjaocI+7fATTGEiyw2GyH61/ieyox2eD+ei0asaJDzxn07DbQpZ66uPqURDER6qJtQRvtghu2NP/qJAIfwQ6FJo7lsaDEPEqK6lxTbuV3eYKLAJjp/Z2Rf1aANkF2uA5XCCDmMZGg2FgSCXjR2XZywM+JhTdFjgSuzJ5ySRgQiPOzOmP2VoYEj7eNyOaXDfRhUUlm8holtzXp84Lf9Mlq6Wy2qruzk6AtArM9ZEwb1DOPFussgr0z/dGcbQ/k/+DmUx/nQJ+IV7MZ/Oa9ZhAW1nu8gLiON/8+pKYrGQQYNJi4SkQj/YAixsZoaAGouOvnYdvR7V76GYodwQM0/zOzAgMBAAECggEACLIFWAjFSAeaWUfwuBSNEyapeNxD9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N87o7HZ6gAbnOY/6hzRv/bNFtvvIZkP1AR5A2lc/gpsIGAxEJtHzJyuckfx6fRhkh4w4NMZ8b0KDO3BAbaDnH5qMINK074OXSEL5cIMUabgeAmOJg==",
            //异步通知地址
            'notify_url' => "https://liveapi.banxued.com/apiadmin/user/alipay_notify",
            //同步跳转
            'return_url' => "https://baidu.com",
            //编码格式
            'charset' => "UTF-8",
            //签名方式(在你生成秘钥的时候，选择的加密方式)
            'sign_type' => "RSA2",
            //支付宝网关（这个是默认的，不用管它）
            'gatewayUrl' => "https://openapi.alipay.com/gateway.do",
            //支付宝公钥,查看地址：https://openhome.alipay.com/platform/keyManage.htm 对应APPID下的支付宝公钥。
            'alipay_public_key' => "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAhxB6iK/ic/9quQOow4pBuB7k4LrezPfx8rg1QYIU8Zvne5Ldh14FdUId4s19pd8km6j+n9gdMkKzBA4yGQxGzSII+fS7kVp1sfvNJiSIhVszdL1Kzpx1n+LPkedF4sXxBYoagPQsbRVo8IoPIl0iTvXZvU/crWMfulhXspTottUPrL1E7GZYP9Sr0GrKZID7IQOOsVYPNjgcqe4qVxrx0Qukaa4F4Roe6WiNM8FviQUWdZhds5mez+o+5Y5B0oE50N8qVemK7yLdAx9LphKTKhGWAvg8UC2pptez5xEtM6aVmgFYZz5Bzcmcrff0RM2BzADIch8IkI//1VtRpfv5uwIDAQAB",
            //日志路径
            'log_path' => "",
        ];

        $refund_amount = $refund_amount / 100;
        //        $trade_no = '2024052522001434301408301006';
        //        $refund_amount = 0.01;

        $RequestBuilder = new AlipayTradeRefundContentBuilder();
        $RequestBuilder->setTradeNo($trade_no);
        //        $RequestBuilder->setOutTradeNo($out_trade_no);
        $RequestBuilder->setRefundAmount($refund_amount);
        //        $RequestBuilder->setRefundReason($refund_reason);
        $RequestBuilder->setOutRequestNo($out_request_no);

        $Response = new AlipayTradeService($config);
        //        $result= $Response->Refund($RequestBuilder);
        try {
            // 可能导致异常的代码
            $result = $Response->Refund($RequestBuilder);

            //            $responseNode = str_replace(".", "_", $request->getApiMethodName()) . "_response";
            $responseNode = "alipay_trade_refund_response";
            $resultCode = $result->$responseNode->code;
            if (!$resultCode || $resultCode != 10000) {
                Log::info('支付宝退款接口返回数据-' . serialize($result->$responseNode));
                throw new Exception('退款接口调用失败:' . serialize($result->$responseNode), 1);
            }

            if ($result->$responseNode->fund_change == "N") {
                // 调用查询接口判断
                $checkRes = $Response->Query($RequestBuilder);
                if (!$checkRes || ($checkRes->$responseNode && $checkRes->$responseNode->refund_status != 'REFUND_SUCCESS')) {
                    Log::info('支付宝退款接口查询数据-' . serialize($checkRes->$checkRes));
                    throw new Exception('退款接口查询失败:' . serialize($checkRes->$checkRes), 1);
                }
            }
            $data['code'] = 0;
            $data['message'] = '退款成功';
            $data['result'] = json_encode($result);
            if (in_array($part_type, [0, 1])) {
                $o = Db::name('siyu_order')->where(['trade_no' => $trade_no])->find();
                //统计提单数据
                $liveId = $o['liveId']; //透传参数  直播ID
                $liveStatus = new LiveStatus($liveId);
                $liveStatus->set_xiaoshoue_tuikuan($o['fee']);
                $liveStatus->set_xiadan_danshu_tuikuan($o['order_num']);
                $liveStatus->set_xiadan_renshu_tuikuan($o['user_id']);
            }
            return $data;

        } catch (Exception $e) {
            // 捕获异常并执行相应的代码
            Log::info('支付宝退款接口异常数据-' . $e->getMessage());
            $data['code'] = $e->getCode();
            $data['message'] = $e->getMessage();
            return $data;

        }
    }
    public function alipay_return_redirect()
    {
        $param = $this->request->param();
        if (isset($param['order_num'])) {
            $order_num = $param['order_num'];
        }
        $where[] = ['order_num', '=', $param['order_num']];
        $order_info = DB::table('xh_siyu_order')->where($where)->order('id desc')->find();

        $user_id = $order_info['user_id'];

        $where1[] = ['id', '=', $user_id];
        $if_exist = DB::table('xh_siyu_user')->where($where1)->order('id desc')->find();

        $user_info['id'] = $if_exist['id'];
        $user_info['name'] = $if_exist['name'];
        $user_info['nickname'] = $if_exist['nickname'];
        $user_info['phone'] = $if_exist['phone'];
        $user_info['openid'] = $if_exist['openid'];
        $user_info['createtime'] = $if_exist['createtime'];
        $user_info['type'] = $if_exist['type'];
        $user_info['wx_avatarurl'] = $if_exist['wx_avatarurl'];
        $user_info['is_im_admin'] = $if_exist['is_im_admin'];

        $front_token = FrontJwtService::createToken($user_info);
        //        dump($front_token);die;
        $url = env('Live.live_host') . '/pages/animate/myorder/myorder?front_token=' . $front_token;
        //        Header("Location: $url");
        return redirect($url);
        //        return redirect((string)url('myorder/myorder'));
    }
    public function test()
    {
        $a1 = array(
            'code' => '',
            'grant_type' => 'authorization_self',
            'shop_id' => '22277625',
        );
        // 序列化参数
        $this->rec_ksort($a1); // 对关联数组中的kv，执行排序，需要递归
        $s = json_encode($a1, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE); // 重新序列化，确保所有key按字典序排序
        // 加入flag，确保斜杠不被escape，汉字不被escape
        $paramJson = $s;
        //        $paramJson = marshal($m);

        $appKey = '7372060210849990182';
        $appSecret = '79440ea4-0cd8-4036-b820-d05b7db20076';
        $method = 'token.create';
        $timestamp = '2024-06-02 15:50:28';
        $v = '2';

        $paramPattern = 'app_key' . $appKey . 'method' . $method . 'param_json' . $paramJson . 'timestamp' . $timestamp . 'v2';
        $signPattern = $appSecret . $paramPattern . $appSecret;
        $sign = hash_hmac("sha256", $signPattern, $appSecret);

        $data['result'] = $sign;
        return Res::ok($data);
    }
    public function rec_ksort(array &$arr)
    {
        $kstring = true;
        foreach ($arr as $k => &$v) {
            if (!is_string($k)) {
                $kstring = false;
            }
            if (is_array($v)) {
                $this->rec_ksort($v);
            }
        }
        if ($kstring) {
            ksort($arr);
        }
    }

    /**
     * 获取支付宝支付  服务商
     * @return \think\response\Json
     * @author cc
     *
     */
    public function getAlipay()
    {
        $param = $this->request->param();

        if (!isset($param['orderid']) || empty($param['orderid'])) {
            return Res::error('请先选择订单！');
        }
        $order_info = DB::table('xh_siyu_order')->where('id', $param['orderid'])->find();
        if (!$order_info) {
            return Res::error('订单不存在！');
        }
        $where = [];
        if (isset($order_info['seller_id']) && !empty($order_info['seller_id'])) {
            $where[] = ['account', '=', $order_info['seller_id']];
            $where[] = ['del', '=', 0];
        } else {
            $where[] = ['flag', '=', 2];
            $where[] = ['state', '=', 1];
            $where[] = ['del', '=', 0];
        }
        $merchantInfo = Db::table('xh_siyu_fuwushang_account')->where($where)->find();
        if (!$merchantInfo) {
            return Res::error('暂时没有激活的支付宝商户！');
        }

        // 沙箱测试
        //        $order_info = [
        //            'order_num' => '70501111111S001111119',
        //            'fee' => '9.9',
        //            'seller_id' => '2088721041849420',
        //        ];
        //        $config = [
        //            'app_id' => '9021000140613279',
        //            'alipay_public_key' => 'MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA2eE9lBRN50GkugrQz1238gG6Ib/r/fTiKuNJ0BNoS63r7DOuF4wylBRN7bRQ6gtea8bYy8vidoIKwJBwDAFB6A822m3NORg/F7kjTse38A8AJawaineEDhK3S+kkHPtf+WG75Zpb90/MH7cvInrBMrhqUoJE9YyndQxdpjGYJCbCGb2NPoyl5Dx4HYFHomv0d40Ijm/c8urIjAymepwm+HNDpGLPDazT9AtRew24k8ijUMw7pQc5Qo1lN4jByZizMfKi8X00Gbbi+5cd4kFLHEgIOfqQvUEmlbe8UsDMRiLubSnOZ9oo91JybIloCCnS/2SjPtOwXQfgqvXyrImgtwIDAQAB',
        //            'merchant_private_key' => 'MIIEogIBAAKCAQEAxnURHESjgOc6G3a1w1OErUExZ3EM+79fTayXhAx53WL29pDA9ZfnzZvQQWz2yevY9EpWMH28OmN7rWTvv7FQMAoi/qi4I8478RuKd6X5iwZ9uPvBc/t8c1zNLSuJQu/4TiS7ZmdzypGbSCtqE3Xqk+5FiPm+7+MQHMYaX4aDok0wgN/GM6IbFcZ9GVzAv7dzBH0x6iKvgsEPZmpXENk5KoYn7xQqzULfLj7gjAbyEV6H252tSdP/zQHQ5hdtK0YL8blqypnvQxBmKt/jp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iy8Hqe+V4t8RobbCIpTn3naPc4oOrpWMNQ1pAoGAR1j8gC1NJOVPW0RwoIj7Tq6ydTjFYBuGPEAXIThvpDLFslwI+xMqMm/4u1tDF5llrCMHD99UEdrzaNV05B5EhQNYitEoy9oHHz+hOOCnIkbxPVqoEOodNr8ZXPgtbf3BvBOZEFJvR7urjE2LGBlhI6koKLWlJVC2hm5VLqXDfxA=',
        //            'notify_url' => 'https://liveapi.banxued.com/apiadmin/alipay/alipay_notify',
        //            'gatewayUrl' => "https://openapi-sandbox.dl.alipaydev.com/gateway.do",
        //            'app_auth_token' => "202408BB7cc83a8b582a453584672c36aca08B73",
        //        ];

        $config = config('alipay');

        $alipayClient = new AopClient();
        $alipayClient->gatewayUrl = $config['gatewayUrl'];
        $alipayClient->appId = $config['app_id'];
        $alipayClient->rsaPrivateKey = $config['merchant_private_key'];
        $alipayClient->alipayrsaPublicKey = $config['alipay_public_key'];
        $alipayClient->signType = "RSA2";
        $alipayClient->postCharset = "UTF-8";
        $alipayClient->format = "JSON";
        $alipayClient->apiVersion = "1.0";

        $info = [
            'out_trade_no' => $order_info['order_num'],
            'total_amount' => $order_info['fee'] / 100,
            'subject' => DB::table('xh_siyu_course')->where('id', $order_info['courseid'])->column('name'),
            'product_code' => 'QUICK_WAP_WAY',
            'seller_id' => !empty($order_info['seller_id']) ? $order_info['seller_id'] : $merchantInfo['account'],
        ];
        $request = new AlipayTradeWapPayRequest();
        $request->setBizContent(json_encode($info));
        $request->setNotifyUrl($config['notify_url']);
        $pageRedirectionData = $alipayClient->pageExecute($request, "POST", $merchantInfo['sp_appid']);
        // 如果需要返回GET请求，请使用
        //         $pageRedirectionData = $alipayClient->pageExecute($request, "GET");
        return Res::ok($pageRedirectionData);

    }
    /**
     * 支付宝支付回调  服务商
     * @return void
     * @author cc
     */
    public function alipay_notify()
    {
        $d['remark'] = "支付宝支付成功后回调地址111111111111";
        Db::table('xh_siyu_user_remark')->save($d);

        $param = $this->request->param();
        if (isset($param)) {
            $d1['remark'] = "支付宝支付成功以后给回调的数据" . json_encode($param);
            DB::table('xh_siyu_user_remark')->save($d1);
        }
        $config = config('alipay');
        $configInfo = [
            'app_id' => $config['app_id'],
            'merchant_private_key' => $config['merchant_private_key'],
            'notify_url' => $config['notify_url'],
            'return_url' => $config['return_url'],
            'charset' => "UTF-8",
            'sign_type' => "RSA2",
            'gatewayUrl' => "https://openapi.alipay.com/gateway.do",
            'alipay_public_key' => $config['alipay_public_key'],
            'log_path' => "",
        ];
        $alipaySevice = new AlipayTradeService($configInfo);
        $alipaySevice->writeLog(var_export($param, true));
        $check = $alipaySevice->check($param);

        if (isset($check)) {
            $d1['remark'] = "我是支付宝支付回调验签的的结果check=" . $check;
            DB::table('xh_siyu_user_remark')->save($d1);
        }
        if ($check) {
            $oo = Db::name('siyu_order')->where(['order_num' => $param['out_trade_no']])->find();
            if ($oo && $param['trade_status'] == 'TRADE_SUCCESS' && $oo['state'] == 0) {
                echo 'success';
                //我这里设置的是，如果返回值是支付成功，那么就把这个订单状态给改状态
                //out_trade_no这个是返回的订单号

                // 获取公域订单
                $unionId = Db::table('xh_siyu_user_order_zhujiao_log')->where(['live_id' => $oo['liveId'], 'user_id' => $oo['user_id']])->value('xh_order_union_id');

                //如果是链接购买
                if (!$unionId) {
                    $unionId = $oo['wx_unionid'];
                }

                $orderId = LiveManagerService::checkXhOrder($unionId);

                $data['state'] = 1;
                $data['trade_no'] = $param['trade_no'];
                $data['pay_time'] = $param['gmt_payment'];
                $data['trade_state_desc'] = '支付成功';
                $data['order_id'] = !empty($orderId) ? $orderId : 0;
                $data['seller_id'] = $param['seller_id'];
                Db::name('siyu_order')->where(['order_num' => $param['out_trade_no']])->save($data);
                //删除改价key
                if ($oo['key']) {
                    $redis = \app\apiadmin\service\data\RedisService::makeService();
                    $redis->del($oo['key']);
                }
                //关联定金
                if ($oo['deposit_ids']) {
                    $deposit_ids = explode(',', $oo['deposit_ids']);
                    if ($deposit_ids) {
                        foreach ($deposit_ids as $id) {
                            $deposit_info = DB::table('xh_siyu_deposit')->where(['id' => $id])->column('actual_payment_fee', 'pay_time');
                            if (!$deposit_info) {
                                continue;
                            }
                            //订单id更新到定金表
                            $data = [
                                'siyu_order_id' => $oo['id'],
                            ];
                            DB::table('xh_siyu_deposit')->where(array('id' => $id))->save($data);
                            //定金金额更新到订单表
                            $update_data = [
                                'deposit_first_fee' => $deposit_info['actual_payment_fee'],
                                'deposit_first_time' => $deposit_info['pay_time'],
                            ];
                            DB::table('xh_siyu_order')->where(['id' => $oo['id']])->update($update_data);
                        }
                    }
                }

                $o = Db::name('siyu_order')->where(['order_num' => $param['out_trade_no']])->find();

                //打日志，做记录
                $m = [];
                $m['liveId'] = $o['liveId'];
                $m['live_user_id'] = $o['user_id'];
                $s = db::table('xh_siyu_invitation_user_signin')->where($m)->find();
                if ($s) {
                    $a = [];
                    $a['chengjiao'] = 3;
                    $a['chengjiao_time'] = date('Y-m-d H:i:s');
                    $a['order_num'] = $o['order_num'];
                    db::table('xh_siyu_invitation_user_signin')->where($m)->save($a);
                } else {
                    $a = [];
                    $a['liveId'] = $o['liveId'];
                    $a['live_user_id'] = $o['user_id'];
                    $a['order_num'] = $o['order_num'];
                    $a['chengjiao'] = 3;
                    $a['chengjiao_time'] = date('Y-m-d H:i:s');
                    db::table('xh_siyu_invitation_user_signin')->insertGetId($a);
                }

                //统计提单数据
                $liveId = $o['liveId'];
                $liveStatus = new LiveStatus($o['liveId']);
                $liveStatus->set_xiaoshoue_yifukuan(intval($o['fee']));
                $liveStatus->set_xiadan_danshu_yifukuan($o['order_num']);
                $liveStatus->set_xiadan_rensu_yifukuan($o['user_id']);

                $liveStatus->remove_xiaoshoue_weifukuan(intval($o['fee']));
                $liveStatus->remove_xiadan_danshu_weifukuan($o['order_num']);
                $liveStatus->remove_xiadan_renshu_weifukuan($o['user_id']);

                //行为记录添加数据详情
                $collection = 'live_event';
                $liveOrder = new LiveUserGetDataService($collection);

                $map = [];
                $map['user_id'] = $o['user_id'] . '';
                $map['liveId'] = $liveId;

                $update = ['$set' => ['event' => '下单']];
                $r = $liveOrder->updateEvent($map, $update);

                MyOrder::afterPayOrder($o);

                // 新增/修改 公域订单状态
                if (!empty($orderId)) {
                    $session = Db::table('xh_siyu_live_manager')->where('id', $liveId)->value('venue');
                    LiveManagerService::getLiveOrderState($liveId, $session, $orderId, 3, $o['wx_unionid'], $o['tutorId'], $o['id'], $o['fee']);
                }

                echo 'success';
            }
            //定金
            $dd = Db::name('siyu_deposit')->where(['deposit_num' => $param['out_trade_no']])->find();
            if ($dd && $param['trade_status'] == 'TRADE_SUCCESS' && $dd['state'] == 0) {
                // echo 'success';

                $data['state'] = 1;
                $data['trade_no'] = $param['trade_no'];
                $data['pay_time'] = $param['gmt_payment'];
                $data['actual_payment_fee'] = $dd['fee'];
                $data['trade_state_desc'] = '支付成功';
                $data['seller_id'] = $param['seller_id'];
                $data['accountid'] = DB::table('xh_siyu_fuwushang_account')->where(['account' => $param['seller_id']])->value('id');
                Db::name('siyu_deposit')->where(['deposit_num' => $param['out_trade_no']])->save($data);

                echo 'success';
            }

        }

    }

    /**
     * 支付宝退款  服务商
     * @param $trade_no
     * @param $refund_amount
     * @param $out_trade_no
     * @param $out_request_no
     * @param $part_type
     * @return \think\response\Json
     * @throws \Exception
     * @author cc
     */
    public static function alipay_refund2($trade_no, $refund_amount, $out_trade_no, $out_request_no, $part_type)
    {
        $merchantToken = "";
        $order_info = DB::table('xh_siyu_order')->where('trade_no', $trade_no)->find();
        if ($order_info) {
            $where = [];
            if (isset($order_info['seller_id']) && !empty($order_info['seller_id'])) {
                $where[] = ['account', '=', $order_info['seller_id']];
                $where[] = ['del', '=', 0];
            } else {
                $where[] = ['flag', '=', 2];
                $where[] = ['state', '=', 1];
                $where[] = ['del', '=', 0];
            }
            $merchantToken = Db::table('xh_siyu_fuwushang_account')->where($where)->value('sp_appid');
        } else {
            $deposit_info = DB::table('xh_siyu_deposit')->where('trade_no', $trade_no)->find();
            if ($deposit_info) {
                if (isset($deposit_info['seller_id']) && !empty($deposit_info['seller_id'])) {
                    $where[] = ['account', '=', $deposit_info['seller_id']];
                    $where[] = ['del', '=', 0];
                } else {
                    $where[] = ['flag', '=', 2];
                    $where[] = ['state', '=', 1];
                    $where[] = ['del', '=', 0];
                }
                $merchantToken = Db::table('xh_siyu_fuwushang_account')->where($where)->value('sp_appid');
            }
        }

        $config = config('alipay');
        $alipayClient = new AopClient();
        $alipayClient->gatewayUrl = $config['gatewayUrl'];
        $alipayClient->appId = $config['app_id'];
        $alipayClient->rsaPrivateKey = $config['merchant_private_key'];
        $alipayClient->alipayrsaPublicKey = $config['alipay_public_key'];
        $alipayClient->signType = "RSA2";
        $alipayClient->postCharset = "UTF-8";
        $alipayClient->format = "JSON";
        $alipayClient->apiVersion = "1.0";
        $refund_amount = $refund_amount / 100;
        $info = [
            'out_trade_no' => $out_trade_no,
            'refund_amount' => $refund_amount,
            'trade_no' => $trade_no,
            'out_request_no' => $out_request_no,
        ];
        $request = new AlipayTradeRefundRequest();
        try {
            if (!$merchantToken) {
                throw new Exception('支付宝商户token获取失败', 1);
            }
            $request->setBizContent(json_encode($info));
            $responseResult = $alipayClient->execute($request, null, $merchantToken);
            $responseApiName = str_replace(".", "_", $request->getApiMethodName()) . "_response";
            $response = $responseResult->$responseApiName;
            if (empty($response->code) || $response->code != 10000) {
                Log::info('支付宝退款接口返回数据-' . serialize($response));
                throw new Exception('退款接口调用失败:' . serialize($response), 1);
            }
            $data['code'] = 0;
            $data['message'] = '退款成功';
            $data['result'] = json_encode($response);
            if (in_array($part_type, [0, 1])) {
                $o = Db::name('siyu_order')->where(['trade_no' => $trade_no])->find();
                //统计提单数据
                $liveId = $o['liveId']; //透传参数  直播ID
                $liveStatus = new LiveStatus($liveId);
                $liveStatus->set_xiaoshoue_tuikuan($o['fee']);
                $liveStatus->set_xiadan_danshu_tuikuan($o['order_num']);
                $liveStatus->set_xiadan_renshu_tuikuan($o['user_id']);
            }
            return $data;

        } catch (Exception $e) {
            // 捕获异常并执行相应的代码
            Log::info('支付宝退款接口异常数据-' . $e->getMessage());
            $data['code'] = $e->getCode();
            $data['message'] = $e->getMessage();
            return $data;
        }
    }

    /**
     * @author: zwx
     * @Description: 添加账号前缀
     * @param {*} $userid
     * @Date: 2024-08-28 16:00:08
     */
    public static function addPreToAccout($userid)
    {

        $pre = env('Live.live_pre'); //账号前缀
        $from_account = $userid;
        $a = strpos($userid, $pre);
        if ($a === false) {
            $from_account = $pre . $from_account;
        }

        return $from_account;

    }

    public function set_user__wx_online_offline_tag()
    {

        $Log = [];
        $param = $this->request->param();

        $userId = $param['userId'];
        $liveId = $param['liveId'];

        $online = $param['online'];
        $online = $online == '1' ? true : false;

        $clearAll = isset($param['clearAll']) ? $param['clearAll'] : false;
        $clearAll = $clearAll == '1' ? true : false;

        // 在线  etbU7dCQAAl7FdxzKGhrky_EgBX7fj1Q
        // 离线 etbU7dCQAAWokEyGS1tveemP8GS3FeNw
        $online_tag = ["etbU7dCQAAl7FdxzKGhrky_EgBX7fj1Q"];
        $offline_tag = ["etbU7dCQAAWokEyGS1tveemP8GS3FeNw"];

        if ($clearAll == true) {
            $tag = ["etbU7dCQAAl7FdxzKGhrky_EgBX7fj1Q", "etbU7dCQAAWokEyGS1tveemP8GS3FeNw"];
        }

        $Log[] = ['userId' => $userId, 'liveId' => $liveId, 'online' => $online, 'clearAll' => $clearAll];
        // 根据 useId 查询
        $userInfos = Db::name('siyu_user')->where(['id' => $userId])->select();
        if (empty($userInfos)) {
            return Res::error("用户信息不存在!");
        }

        $unionids = [];
        foreach ($userInfos as $k => $v) {
            $unionids[] = $v['unionid'];
        }

        $Log[] = ['unionids' => $unionids, "SQL" => Db::name('siyu_user')->getLastSql()];

        // select * from xh_siyu_user_order_zhujiao_log
        // where xh_siyu_user_order_zhujiao_log.live_id = 732 and
        // (xh_siyu_user_order_zhujiao_log.xh_order_union_id  = "ogn1qw8SN5DrnoO7pNA_K1Z8YRZM" or  xh_siyu_user_order_zhujiao_log.user_union_id = "ogn1qw8SN5DrnoO7pNA_K1Z8YRZM" )

        $zhujiao_infos = Db::name('siyu_user_order_zhujiao_log')
            ->where(['live_id' => $liveId])
            ->where("xh_order_union_id|user_union_id", "in", $unionids)
            ->select();

        if (empty($zhujiao_infos)) {
            return Res::error("用户未找到助教信息！");
        }

        $user_union_ids = [];
        foreach ($zhujiao_infos as $k => $v) {
            $user_union_ids[] = $v['user_union_id'];
        }

        $Log[] = ['user_union_ids' => $user_union_ids, "SQL" => Db::name('siyu_user_order_zhujiao_log')->getLastSql()];
        // 去掉重复的
        $user_union_ids = array_unique($user_union_ids);

        // select * from xh_siyu_invitation_user where xh_siyu_invitation_user.liveId = 732 AND xh_siyu_invitation_user.wx_unionid IN ("ogn1qw8SN5DrnoO7pNA_K1Z8YRZM","ogn1qw8SN5DrnoO7pNA_K1Z8YRZM","ogn1qw8SN5DrnoO7pNA_K1Z8YRZM")

        $invitation_user_infos = Db::name('siyu_invitation_user')
            ->where(['liveId' => $liveId])
            ->where("wx_unionid", "in", $user_union_ids)
            ->select();

        if (empty($invitation_user_infos)) {
            // return "用户未找到邀请信息！";
            return Res::error("用户未找到邀请信息！");
        }

        $retList = [];
        foreach ($invitation_user_infos as $key => $value) {
            $external_userid = $value['external_userid'];
            $sender = $value['sender'];

            if ($clearAll == true) {
                $ret = InvitationService::marktag($sender, $external_userid, [], array_merge($online_tag, $offline_tag));
                $retList[] = $ret;
                $Log[] = ['ret' => $ret, 'clearAll' => $clearAll, 'external_userid' => $external_userid, 'sender' => $sender];
            } else {
                if ($online == true) {
                    $ret = InvitationService::marktag($sender, $external_userid, $online_tag, $offline_tag);
                    $retList[] = $ret;
                    $Log[] = ['ret' => $ret, 'clearAll' => $clearAll, 'external_userid' => $external_userid, 'sender' => $sender];

                } else {
                    $ret = InvitationService::marktag($sender, $external_userid, $offline_tag, $online_tag, );
                    $retList[] = $ret;
                    $Log[] = ['ret' => $ret, 'clearAll' => $clearAll, 'external_userid' => $external_userid, 'sender' => $sender];

                }

            }
        }
        ob_clean();
        return Res::ok([$retList, $Log]);
    }

    public function clean_all_wxwork_tag()
    {
        $param = $this->request->param();

        $liveId = $param['liveId'];

        $invitation_user_infos = Db::name('siyu_invitation_user')
            ->where(['liveId' => $liveId])
            ->select()->toArray();

        if (empty($invitation_user_infos)) {
            return Res::error("用户未找到邀请信息！");
        }

        $tag = ["etbU7dCQAAl7FdxzKGhrky_EgBX7fj1Q", "etbU7dCQAAWokEyGS1tveemP8GS3FeNw"];

        foreach ($invitation_user_infos as $key => $value) {
            $external_userid = $value['external_userid'];
            $sender = $value['sender'];

            print_r([$sender, $external_userid, $tag]);
            $ret = InvitationService::markTag($sender, $external_userid, [], $tag);

        }

    }

    public function GetCourseTags()
    {
        $param = $this->request->param();
        if (!isset($param['liveId']) && !isset($param['userId'])) {
            return Res::error('参数错误');
        }
        $ret = InvitationService::markTagWithLiveIdAndUserId($param['liveId'], $param['userId']);
    }

}
